import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Statistic, Select, Button, Space, message } from 'antd';
import {
  DatabaseOutlined,
  ShareAltOutlined,
  NodeIndexOutlined,
  UserOutlined,
  TrophyOutlined,
  RiseOutlined
} from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { entityApi, relationApi } from '../../../services/api';

const { Option } = Select;

const DashboardHome = () => {
  const [timeDimension, setTimeDimension] = useState('周');
  const [loading, setLoading] = useState(false);
  
  // 统计数据状态
  const [stats, setStats] = useState({
    entityCount: 0,
    relationCount: 0,
    typeCount: 0
  });
  
  // 类型分布数据
  const [typeDistribution, setTypeDistribution] = useState([]);
  
  // 活跃度趋势数据
  const [activityTrend, setActivityTrend] = useState({});

  // 获取统计数据
  const fetchStats = async () => {
    try {
      setLoading(true);
      
      // 获取实体统计
      let entityStats;
      try {
        entityStats = await entityApi.getUserStats();
      } catch (error) {
        console.log('用户实体统计接口不可用，使用全局统计');
        entityStats = await entityApi.getStats();
      }
      
      // 获取关系统计
      let relationStats;
      try {
        relationStats = await relationApi.getUserStats();
      } catch (error) {
        console.log('用户关系统计接口不可用，使用全局统计');
        relationStats = await relationApi.getStats();
      }
      
      // 合并统计数据
      if (entityStats?.success && relationStats?.success) {
        setStats({
          entityCount: entityStats.data.entityCount || 0,
          relationCount: relationStats.data.relationCount || 0,
          typeCount: (entityStats.data.typeCount || 0) + (relationStats.data.typeCount || 0)
        });
        
        // 设置类型分布数据（优先使用关系类型分布）
        if (relationStats.data.typeDistribution && relationStats.data.typeDistribution.length > 0) {
          setTypeDistribution(relationStats.data.typeDistribution);
        } else if (entityStats.data.typeDistribution && entityStats.data.typeDistribution.length > 0) {
          setTypeDistribution(entityStats.data.typeDistribution);
        } else {
          setTypeDistribution([]);
        }
        
        // 设置活跃度趋势数据（优先使用关系活跃度）
        if (relationStats.data.activityTrend && Object.keys(relationStats.data.activityTrend).length > 0) {
          setActivityTrend(relationStats.data.activityTrend);
        } else if (entityStats.data.activityTrend && Object.keys(entityStats.data.activityTrend).length > 0) {
          setActivityTrend(entityStats.data.activityTrend);
        } else {
          setActivityTrend({});
        }
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
      message.error('获取统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 初始化加载数据
  useEffect(() => {
    fetchStats();
  }, []);

  // 统计卡片数据
  const statsData = [
    {
      title: '实体总数',
      value: stats.entityCount,
      icon: <DatabaseOutlined style={{ color: '#1890ff' }} />,
      color: '#1890ff',
      suffix: '个'
    },
    {
      title: '关系总数',
      value: stats.relationCount,
      icon: <ShareAltOutlined style={{ color: '#52c41a' }} />,
      color: '#52c41a',
      suffix: '条'
    },
    {
      title: '类型种类',
      value: stats.typeCount,
      icon: <NodeIndexOutlined style={{ color: '#faad14' }} />,
      color: '#faad14',
      suffix: '种'
    }
  ];

  // 渲染类型分布图表
  const renderTypeDistributionChart = () => {
    if (typeDistribution.length === 0) {
      return (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center', 
          height: '300px',
          color: '#999',
          fontSize: '14px'
        }}>
          暂无数据
        </div>
      );
    }

    return (
      <Row>
        <Col span={14}>
          <ReactECharts
            option={{
              tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
              },
              series: [
                {
                  name: '类型分布',
                  type: 'pie',
                  radius: ['45%', '75%'],
                  center: ['50%', '50%'],
                  avoidLabelOverlap: false,
                  itemStyle: {
                    borderRadius: 8,
                    borderColor: '#fff',
                    borderWidth: 2
                  },
                  label: {
                    show: false
                  },
                  emphasis: {
                    itemStyle: {
                      shadowBlur: 10,
                      shadowOffsetX: 0,
                      shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                  },
                  labelLine: {
                    show: false
                  },
                  data: typeDistribution.map(item => ({
                    value: item.count || item.value,
                    name: item.type,
                    itemStyle: {
                      color: item.color
                    }
                  }))
                }
              ]
            }}
            style={{ height: '280px' }}
          />
        </Col>
        <Col span={10}>
          <div style={{ paddingLeft: '20px', paddingTop: '40px' }}>
            {typeDistribution.map((item, index) => (
              <div key={index} style={{ 
                display: 'flex', 
                alignItems: 'center', 
                marginBottom: '16px',
                fontSize: '13px'
              }}>
                <div style={{
                  width: '12px',
                  height: '12px',
                  borderRadius: '50%',
                  backgroundColor: item.color,
                  marginRight: '8px',
                  flexShrink: 0
                }} />
                <div style={{ 
                  flex: 1,
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center'
                }}>
                  <span style={{ color: '#666' }}>{item.type}</span>
                  <span style={{ 
                    fontWeight: 'bold',
                    color: '#333',
                    marginLeft: '8px'
                  }}>
                    {item.value || Math.round((item.count / typeDistribution.reduce((sum, t) => sum + (t.count || 0), 0)) * 100)}%
                  </span>
                </div>
              </div>
            ))}
          </div>
        </Col>
      </Row>
    );
  };

  // 渲染活跃度趋势图表
  const renderActivityTrendChart = () => {
    const trendData = activityTrend[timeDimension];
    
    if (!trendData) {
      return (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center', 
          height: '300px',
          color: '#999',
          fontSize: '14px'
        }}>
          暂无数据
        </div>
      );
    }

    const categories = trendData.categories || [];
    const barData = trendData.barData || [];
    const lineData = trendData.lineData || [];

    return (
      <ReactECharts
        option={{
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross',
              crossStyle: {
                color: '#999'
              }
            }
          },
          legend: {
            data: ['新增数量', '活跃度'],
            bottom: 0,
            textStyle: { fontSize: 11 }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '15%',
            top: '10%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: categories,
              axisPointer: {
                type: 'shadow'
              },
              axisLabel: { fontSize: 11 }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '新增数量',
              position: 'left',
              axisLabel: {
                fontSize: 11,
                formatter: '{value}'
              }
            },
            {
              type: 'value',
              name: '活跃度',
              position: 'right',
              axisLabel: {
                fontSize: 11,
                formatter: '{value}'
              }
            }
          ],
          series: [
            {
              name: '新增数量',
              type: 'bar',
              yAxisIndex: 0,
              itemStyle: {
                borderRadius: [4, 4, 0, 0],
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    {
                      offset: 0,
                      color: '#1890ff'
                    },
                    {
                      offset: 1,
                      color: '#69c0ff'
                    }
                  ]
                }
              },
              data: barData
            },
            {
              name: '活跃度',
              type: 'line',
              yAxisIndex: 1,
              smooth: true,
              lineStyle: {
                width: 3,
                color: '#722ed1'
              },
              itemStyle: {
                color: '#722ed1'
              },
              symbol: 'circle',
              symbolSize: 6,
              data: lineData
            }
          ]
        }}
        style={{ height: '300px' }}
      />
    );
  };

  return (
    <div style={{ 
      padding: '24px', 
      background: '#f7f8fa',
      minHeight: '100%',
      overflowX: 'hidden'
    }}>
      {/* 欢迎区域 */}
      <Card style={{ marginBottom: '24px', borderRadius: '8px' }}>
        <Row align="middle">
          <Col flex="auto">
            <div>
              <h2 style={{ margin: 0, color: '#1d2129' }}>
                欢迎使用知识图谱管理系统
              </h2>
              <p style={{ margin: '8px 0 0 0', color: '#86909c' }}>
                构建智能化的知识网络，发现数据间的深层关联
              </p>
            </div>
          </Col>
          <Col>
            <Space>
              <Button type="primary" icon={<RiseOutlined />}>
                查看详情
              </Button>
              <Button icon={<TrophyOutlined />}>
                使用指南
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: '24px' }}>
        {statsData.map((stat, index) => (
          <Col span={8} key={index}>
            <Card style={{ borderRadius: '8px' }}>
              <Statistic
                title={stat.title}
                value={stat.value}
                valueStyle={{ color: stat.color }}
                prefix={stat.icon}
                suffix={stat.suffix}
                loading={loading}
              />
            </Card>
          </Col>
        ))}
      </Row>

      {/* 图表区域 */}
      <Row gutter={16}>
        <Col span={12}>
          <Card 
            title="类型分布" 
            bordered={false}
            style={{ borderRadius: '8px' }}
          >
            {renderTypeDistributionChart()}
          </Card>
        </Col>
        <Col span={12}>
          <Card 
            title="活跃度趋势" 
            bordered={false}
            style={{ borderRadius: '8px' }}
            extra={
              <Select 
                value={timeDimension} 
                onChange={setTimeDimension}
                style={{ width: 100 }}
              >
                <Option value="周">近7天</Option>
                <Option value="月">近30天</Option>
                <Option value="年">近一年</Option>
              </Select>
            }
          >
            {renderActivityTrendChart()}
          </Card>
        </Col>
      </Row>
    </div>
  );
};

export default DashboardHome;